<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton :icon="Plus" @click="showDialog('add')">新增</ElButton>
          </template>
        </ArtTableHeader>
        <!-- 表格 -->
        <art-table
          :data="tableData"
          :loading="loading"
          v-model:currentPage="queryParams.page"
          v-model:pageSize="queryParams.size"
          :total="total"
          @size-change="getTableData"
          @current-change="getTableData"
        >
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '添加内容' : '编辑内容'"
          width="40%"
        >
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="80px"
            :disabled="disabled"
          >
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="分类" prop="type">
                  <el-select v-model="formData.type">
                    <el-option
                      v-for="type in typeList"
                      :key="type.value"
                      :label="type.label"
                      :value="type.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="日期" prop="day">
                  <el-select v-model="formData.day">
                    <el-option
                      v-for="day in weekDays"
                      :key="day.value"
                      :label="day.label"
                      :value="day.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="添加食物" prop="food_ids">
              <div style="display: flex; flex-direction: column; width: 100%">
                <el-button style="width: 100px" v-if="isDetail" @click="showFoodDialog"
                  >添加食物</el-button
                >
                <art-table
                  v-if="foods.length > 0"
                  :data="foods"
                  :loading="foodsLoading"
                  :pagination="false"
                  :height="foods.length > 3 ? 300 : '100%'"
                >
                  <template #default>
                    <el-table-column prop="title" label="名称" />
                    <el-table-column prop="pic" label="封面">
                      <template #default="scope">
                        <ArtImagePreview :src="scope.row.pic" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="heat" label="热量" />
                    <el-table-column prop="desc" label="描述" />
                    <el-table-column prop="num" label="数量" />
                    <el-table-column prop="operation" label="操作">
                      <template #default="{ row }">
                        <el-button
                          type="danger"
                          size="small"
                          :icon="Delete"
                          @click="handleDelFood(row)"
                        ></el-button>
                      </template>
                    </el-table-column>
                  </template>
                </art-table>
              </div>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-tooltip :content="formData.status === 1 ? '上架' : '下架'" placement="top">
                <el-switch v-model="formData.status" :active-value="1" :inactive-value="-1" />
              </el-tooltip>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :disabled="disabled">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
      <el-dialog v-model="dialogFoods" title="食物列表" width="60%" top="4vh">
        <recipes
          ref="recipesRef"
          v-if="dialogFoods"
          :showAdd="false"
          @chooseRows="handleRows"
          :tableRowData="foods"
        />
      </el-dialog>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus'
  import { View, Delete, Edit, Plus } from '@element-plus/icons-vue'
  import type { FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { FoodsService } from '@/api/foods'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'
  import recipes from './recipes.vue'
  import { deepClone } from '@/utils/utils'

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const dialogFoods = ref(false)
  const foods = ref([])
  const foodsLoading = ref(false)
  const isDetail = ref(true)
  const loading = ref(false)
  const tableData = ref<any>([])
  const disabled = ref(false)
  const recipesRef = ref(null)
  const typeList = [
    { value: 1, label: '早餐' },
    { value: 2, label: '午餐' },
    { value: 3, label: '晚餐' }
  ]
  const weekDays = reactive([
    { value: 1, label: '周一' },
    { value: 2, label: '周二' },
    { value: 3, label: '周三' },
    { value: 4, label: '周四' },
    { value: 5, label: '周五' },
    { value: 6, label: '周六' },
    { value: 7, label: '周日' }
  ])
  const formData = reactive({
    type: '',
    day: '',
    food_ids: '',
    status: 1
  })

  const total = ref(0)
  const queryParams = reactive({
    page: 1,
    size: 12
  })
  onMounted(() => {
    getTableData()
  })

  //添加食物
  const handleRows = (rows: any) => {
    let ids = []
    let myFoods = []
    rows.forEach((item: any) => {
      ids.push(item.id)
      myFoods.push(item)
    })
    formData.food_ids = ids.join(',')
    foods.value = myFoods
    console.log('foods', foods.value)
    console.log('food_ids', formData.food_ids)
    dialogFoods.value = false
  }

  // 删除食物
  const handleDelFood = (row: any) => {
    const index = foods.value.findIndex((item: any) => item.id == row.id)
    // const idIndex = formData.food_ids.split(',').findIndex((id) => id == row.id)
    foods.value.splice(index, 1)
    formData.food_ids = formData.food_ids
      .split(',')
      .filter((id) => id != row.id)
      .join(',')
    console.log('id==food_ids', row.id, formData.food_ids)
  }
  // 显示食物dialog
  const showFoodDialog = () => {
    dialogFoods.value = true
  }
  const getTagType = (state: number) => {
    switch (state) {
      case 1:
        return 'success'
      case -1:
        return 'danger'
      default:
        return 'info'
    }
  }

  const buildTagText = (status: number) => {
    let text = ''
    if (status === 1) {
      text = '上架'
    } else if (status === -1) {
      text = '下架'
    }
    return text
  }
  // 列配置
  const columnOptions = [
    { label: '类型', prop: 'type' },
    { label: '日期', prop: 'day' },
    { label: '状态', prop: 'status' },
    { label: '创建日期', prop: 'create_time' },
    { label: '操作', prop: 'operation' }
  ]
  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    // { type: 'selection' }, // 勾选列
    // { type: 'expand', label: '展开', width: 80 }, // 展开列
    // { type: 'index', label: '序号', width: 80 }, // 序号列
    {
      prop: 'type',
      label: '类型',
      align: 'center',
      formatter: (row) => {
        return h(ElTag, { type: 'success' }, () => typeList.find((i) => i.value == row.type).label)
      }
    },
    {
      prop: 'day',
      label: '日期',
      align: 'center',
      sortable: true,
      formatter: (row) => {
        return h(ElTag, { type: 'success' }, () => weekDays.find((i) => i.value == row.day).label)
      }
    },
    {
      prop: 'status',
      label: '状态',
      align: 'center',
      formatter: (row) => {
        return h(ElTag, { type: getTagType(row.status) }, () => buildTagText(row.status))
      }
    },
    {
      prop: 'create_time',
      label: '创建日期',
      align: 'center'
    },
    {
      prop: 'operation',
      label: '操作',
      width: 220,
      align: 'center',
      fixed: 'right', // 固定在右侧
      // disabled: true,
      formatter: (row: any) => {
        return h('div', { class: 'option' }, [
          h(
            ElButton,
            {
              size: 'small',
              icon: Edit,
              text: true,
              onClick: () => showDialog('edit', row)
            },
            () => '编辑'
          ),
          h(
            ElButton,
            {
              size: 'small',
              type: 'danger',
              icon: Delete,
              text: true,
              onClick: () => deleteTableRow(row)
            },
            () => '删除'
          ),
          h(
            ElButton,
            {
              size: 'small',
              icon: View,
              text: true,
              onClick: () => showDialog('detail', row)
            },
            () => '详情'
          )
        ])
      }
    }
  ])
  // 获取商品列表
  const getTableData = async () => {
    loading.value = true
    const res = await FoodsService.getFoodsList(queryParams)
    total.value = res.data.total
    tableData.value = res.data.data
    loading.value = false
  }
  // 刷新
  const handleRefresh = () => {
    getTableData()
  }
  const setFromData = (row: any) => {
    let copyFoods = []
    copyFoods = deepClone(row.foods) as any
    formData.type = row.type
    formData.day = row.day
    formData.food_ids = row.food_ids
    formData.status = row.status
    formData.id = row.id
    foods.value = copyFoods
  }
  const resetFromData = () => {
    formData.type = ''
    formData.day = ''
    formData.food_ids = ''
    formData.status = 1
    foods.value = []
  }
  // 显示弹窗
  const showDialog = (type: string, row?: any) => {
    disabled.value = false
    if (type === 'edit' && row) {
      setFromData(row)
      isDetail.value = true
    } else if (type === 'detail' && row) {
      setFromData(row)
      isDetail.value = false
      disabled.value = true
    } else {
      resetFromData()
      isDetail.value = true
    }
    dialogVisible.value = true
    dialogType.value = type
  }
  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm('确定要删除该列吗？', '删除列表', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return FoodsService.delFood(row.id)
      })
      .then(() => {
        getTableData()
        ElMessage.success('删除成功')
      })
  }

  const rules = reactive<FormRules>({
    type: [{ required: true, message: '请选择食物分类', trigger: 'blur' }],
    day: [{ required: true, message: '请输入日期', trigger: 'blur' }],
    food_ids: [{ required: true, message: '请选择食物', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = () => {
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await FoodsService.addFoods(formData)
        } else {
          await FoodsService.updateFoods(formData)
        }
        await getTableData()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.option .el-button + .el-button) {
    margin-left: 0;
  }
</style>
